package com.winning.bi.etl;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
import com.winning.bi.jdbc.dao.Dao;

/**
 * 创建新的任务表
 * 
 * 
 * @author 张大川
 *
 */
public class NewTask extends JFrame {

	/**
	 *
	 * ADD EXIT PRIMARY ALL FETCH PRINT ALTER FILE PRIVILEGES AND FILLFACTOR
	 * PROC ANY FLOPPY PROCEDURE AS FOR PROCESSEXIT ASC FOREIGN PUBLIC
	 * AUTHORIZATION FREETEXT RAISERROR AVG FREETEXTTABLE READ BACKUP FROM
	 * READTEXT BEGIN FULL RECONFIGURE BETWEEN GOTO REFERENCES BREAK GRANT
	 * REPEATABLE BROWSE GROUP REPLICATION BULK HAVING RESTORE BY HOLDLOCK
	 * RESTRICT CASCADE IDENTITY RETURN CASE IDENTITY_INSERT REVOKE CHECK
	 * IDENTITYCOL RIGHT CHECKPOINT IF ROLLBACK CLOSE IN ROWCOUNT CLUSTERED
	 * INDEX ROWGUIDCOL COALESCE INNER RULE COLUMN INSERT SAVE COMMIT INTERSECT
	 * SCHEMA COMMITTED INTO SELECT COMPUTE IS SERIALIZABLE CONFIRM ISOLATION
	 * SESSION_USER CONSTRAINT JOIN SET CONTAINS KEY SETUSER CONTAINSTABLE KILL
	 * SHUTDOWN CONTINUE LEFT SOME CONTROLROW LEVEL STATISTICS CONVERT LIKE SUM
	 * COUNT LINENO SYSTEM_USER CREATE LOAD TABLE CROSS MAX TAPE CURRENT MIN
	 * TEMP CURRENT_DATE MIRROREXIT TEMPORARY CURRENT_TIME NATIONAL TEXTSIZE
	 * CURRENT_TIMESTAMP NOCHECK THEN CURRENT_USER NONCLUSTERED TO CURSOR NOT
	 * TOP DATABASE NULL TRAN DBCC NULLIF TRANSACTION DEALLOCATE OF TRIGGER
	 * DECLARE OFF TRUNCATE DEFAULT OFFSETS TSEQUAL DELETE ON UNCOMMITTED DENY
	 * ONCE UNION DESC ONLY UNIQUE DISK OPEN UPDATE DISTINCT OPENDATASOURCE
	 * UPDATETEXT DISTRIBUTED OPENQUERY USE DOUBLE OPENROWSET USER DROP OPTION
	 * VALUES DUMMY OR VARYING DUMP ORDER VIEW ELSE OUTER WAITFOR END OVER WHEN
	 * ERRLVL PERCENT WHERE ERROREXIT PERM WHILE ESCAPE PERMANENT WITH EXCEPT
	 * PIPE WORK EXEC PLAN WRITETEXT EXECUTE PRECISION EXISTS PREPARE
	 */
	public static final String[] KEYS = { "ADD", "EXIT", "PRIMARY", "ALL", "FETCH", "PRINT", "ALTER", "FILE",
			"PRIVILEGES", "AND", "FILLFACTOR", "PROC", "ANY", "FLOPPY", "PROCEDURE", "AS", "FOR", "PROCESSEXIT", "ASC",
			"FOREIGN", "PUBLIC", "AUTHORIZATION", "FREETEXT", "RAISERROR", "AVG", "FREETEXTTABLE", "READ", "BACKUP",
			" READTEXT", "BEGIN", "FULL", "RECONFIGURE", "BETWEEN", "GOTO", "REFERENCES", "BETWEEN", "BREAK", "GRANT",
			"REPEATABLE", "BROWSE", "GROUP", "REPLICATION", "BULK", "HAVING", "RESTORE", "BY", "HOLDLOCK", "RESTRICT",
			"CASCADE", "IDENTITY", "RETURN", "CASE", "IDENTITY_INSERT", "REVOKE", "CHECK", "IDENTITYCOL", "RIGHT",
			"CHECKPOINT", "IF", "ROLLBACK", "CLOSE", "IN", "ROWCOUNT", "CLUSTERED", "INDEX", "ROWGUIDCOL", "COALESCE",
			"INNER", "RULE", "COLUMN", "INSERT", "SAVE", "COMMIT", "INTERSECT", "SCHEMA", "COMMITTED", "INTO", "SELECT",
			"COMPUTE", "IS", "SERIALIZABLE", "CONFIRM", "ISOLATION", "SESSION_USER", "CONSTRAINT", "JOIN", "SET",
			"CONTAINS", "KEY", "SETUSER", "CONTAINSTABLE", "KILL", "SHUTDOWN", "CONTINUE", "LEFT", "SOME", "CONTROLROW",
			"LEVEL", "STATISTICS", "CONVERT", "LIKE", "SUM", "COUNT", "LINENO", "SYSTEM_USER", "CREATE", "LOAD",
			"TABLE", "CROSS", "MAX", "TAPE", "CURRENT", "MIN", "TEMP", "CURRENT_DATE", "MIRROREXIT", "TEMPORARY",
			"CURRENT_TIME", "NATIONAL", "TEXTSIZE", "CURRENT_TIMESTAMP", "NOCHECK", "THEN", "CURRENT_USER",
			"NONCLUSTERED", "TO", "CURSOR", "NOT", "TOP", "DATABASE", "NULL", "TRAN", "DBCC", "NULLIF", "TRANSACTION",
			"DEALLOCATE", "OF", "TRIGGER", "DECLARE", "OFF", "TRUNCATE", "DEFAULT", "OFFSETS", "TSEQUAL", "DELETE",
			"ON", "UNCOMMITTED", "DENY", "ONCE", "UNION", "DESC", "ONLY", "UNIQUE", "DISK", "OPEN", "UPDATE",
			"DISTINCT", "OPENDATASOURCE", "UPDATETEXT", "DISTRIBUTED", "OPENQUERY", "USE", "DOUBLE", "OPENROWSET",
			"USER", "DROP", "OPTION", "VALUES", "DUMMY", "OR", "VARYING", "DUMP", "ORDER", "VIEW", "ELSE", "OUTER",
			"WAITFOR", "END", "OVER", "WHEN", "ERRLVL", "PERCENT", "WHERE", "ERROREXIT", "PERM", "WHILE", "ESCAPE",
			"PERMANENT", "WITH", "EXCEPT", "PIPE", "WORK", "EXEC", "PLAN", "WRITETEXT", "EXECUTE", "PRECISION",
			"EXISTS", "PREPARE" };
	// CONTAINS KEY SETUSER
	// CONTAINSTABLE KILL SHUTDOWN
	// CONTINUE LEFT SOME
	// CONTROLROW LEVEL STATISTICS
	// CONVERT LIKE SUM
	// COUNT LINENO SYSTEM_USER
	// CREATE LOAD TABLE
	// CROSS MAX TAPE
	// CURRENT MIN TEMP
	// CURRENT_DATE MIRROREXIT TEMPORARY
	// CURRENT_TIME NATIONAL TEXTSIZE
	// CURRENT_TIMESTAMP NOCHECK THEN
	// CURRENT_USER NONCLUSTERED TO
	// CURSOR NOT TOP
	// DATABASE NULL TRAN
	// DBCC NULLIF TRANSACTION
	// DEALLOCATE OF TRIGGER
	// DECLARE OFF TRUNCATE
	// DEFAULT OFFSETS TSEQUAL
	// DELETE ON UNCOMMITTED
	// DENY ONCE UNION
	// DESC ONLY UNIQUE
	// DISK OPEN UPDATE
	// DISTINCT OPENDATASOURCE UPDATETEXT
	// DISTRIBUTED OPENQUERY USE
	// DOUBLE OPENROWSET USER
	// DROP OPTION VALUES
	// DUMMY OR VARYING
	// DUMP ORDER VIEW
	// ELSE OUTER WAITFOR
	// END OVER WHEN
	// ERRLVL PERCENT WHERE
	// ERROREXIT PERM WHILE
	// ESCAPE PERMANENT WITH
	// EXCEPT PIPE WORK
	// EXEC PLAN WRITETEXT
	// EXECUTE PRECISION
	// EXISTS PREPARE}
	private static final long serialVersionUID = 1L;
	public static final String dataSource = "dataSource";
	public static final String dataTask = "dataTask";
	public static final String dataTarget = "dataTarget";
	private JPanel contentPane;
	String name;
	String source;
	String targetTable;

	ClassPathXmlApplicationContext ac;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					NewTask frame = new NewTask();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public ClassPathXmlApplicationContext getAc() {
		return ac;
	}

	public void setAc(ClassPathXmlApplicationContext ac) {
		this.ac = ac;
	}

	/**
	 * Create the frame.
	 * 
	 * @throws ConfigurationException
	 */
	public NewTask() throws ConfigurationException {
		super("新建ETL任务");
		Configuration config = new PropertiesConfiguration("config/amqp.properties");
		// config.get
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 500, 350);
		JPanel jPanel = new JPanel();
		contentPane = new JPanel();

		jPanel.setBorder(new EmptyBorder(30, 30, 30, 30));

		setContentPane(jPanel);
		JPanel jPanel2 = new JPanel();

		JButton button4 = new JButton("确定");

		JButton button3 = new JButton("取消");

		jPanel2.add(button3);
		jPanel2.add(button4);

		contentPane.setLayout(new FormLayout(
				new ColumnSpec[] { ColumnSpec.decode("40px"), ColumnSpec.decode("80px"),
						FormSpecs.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("150px"), ColumnSpec.decode("140px") },
				new RowSpec[] { RowSpec.decode("21px"), RowSpec.decode("21px"), FormSpecs.LINE_GAP_ROWSPEC,
						RowSpec.decode("21px"), FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("21px"),
						FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("21px"), FormSpecs.LINE_GAP_ROWSPEC,
						RowSpec.decode("21px"), FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("21px"),
						FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("21px") }));
		contentPane.add(new JLabel("名称"), "2, 2, left, center");
		JTextField nameField = new JTextField();

		contentPane.add(nameField, "4, 2, fill, top");
		contentPane.add(new JLabel("源数据表"), "2, 4, left, center");
		JTextField sourceField = new JTextField();
		sourceField.setEnabled(false);
		contentPane.add(sourceField, "4, 4, fill, top");
		JButton button = new JButton("从数据库中选择");
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

				TargetList list = new TargetList(ac, dataSource, "daoSource");

				list.setVisible(true);
				list.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
				list.addWindowListener(new WindowAdapter() {
					public void windowClosing(WindowEvent e) {
						System.out.println("[选择的表]" + list.getTableName());
						sourceField.setText(list.getTableName());
					}

				});
			}
		});
		contentPane.add(button, "5, 4, left, top");
		contentPane.add(new JLabel("目标数据表"), "2, 6, left, center");
		JTextField target = new JTextField();
		target.setEnabled(false);
		contentPane.add(target, "4, 6, fill, top");
		JButton button_1 = new JButton("从数据库中选择");
		button_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				TargetList list = new TargetList(ac, dataTarget, "daoTarget");

				list.setVisible(true);
				list.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
				list.addWindowListener(new WindowAdapter() {
					public void windowClosing(WindowEvent e) {
						System.out.println("[选择的表]" + list.getTableName());
						target.setText(list.getTableName());
					}

				});
			}
		});

		contentPane.add(button_1, "5, 6, left, top");
		contentPane.add(new JLabel("任务corn"), "2, 8, left, center");
		JTextField cron = new JTextField();
		contentPane.add(cron, "4, 8, fill, top");
		contentPane.add(new JLabel("时间戳"), "2, 10, left, center");
		JTextField rowversion = new JTextField();
		contentPane.add(rowversion, "4, 10, fill, top");
		contentPane.add(new JLabel("字段映射"), "2, 12, left, center");
		JButton button_2 = new JButton("添加映射");
		JTextField relationship = new JTextField();
		button_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (StringUtils.isBlank(sourceField.getText()) && StringUtils.isBlank(target.getText())) {
					JOptionPane.showMessageDialog(contentPane, "没有选择数据表", "提示", JOptionPane.WARNING_MESSAGE);
					return;
				} else {
					// relationship.setText("");
					DataList frame = new DataList(sourceField.getText(), target.getText());
					frame.setVisible(true);

					frame.addWindowListener(new WindowAdapter() {
						public void windowClosing(WindowEvent e) {

							relationship.setText(frame.getReturnString());
						}

					});

				}
			}
		});
		contentPane.add(button_2, "5, 12, left, top");

		relationship.setEnabled(false);
		contentPane.add(relationship, "4, 12, fill, top");

		jPanel.add(contentPane, BorderLayout.NORTH);
		jPanel.add(jPanel2, BorderLayout.SOUTH);
		button4.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				/**
				 * 保存
				 * 
				 * 
				 * 
				 */
				if (StringUtils.isBlank(nameField.getText())) {
					JOptionPane.showMessageDialog(contentPane, "没有填写任务名", "提示", JOptionPane.WARNING_MESSAGE);
					return;
				}

				else if (StringUtils.isBlank(sourceField.getText())) {
					JOptionPane.showMessageDialog(contentPane, "没有选择源数据表", "提示", JOptionPane.WARNING_MESSAGE);
					return;
				} else if (StringUtils.isBlank(target.getText())) {
					JOptionPane.showMessageDialog(contentPane, "没有选择目标数据表", "提示", JOptionPane.WARNING_MESSAGE);
					return;
				} else if (StringUtils.isBlank(cron.getText())) {
					JOptionPane.showMessageDialog(contentPane, "没有填写cron表达式", "提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				// else if (StringUtils.isBlank(rowversion.getText())) {
				// JOptionPane.showMessageDialog(contentPane, "没有填写timestamp",
				// "提示", JOptionPane.WARNING_MESSAGE);
				// return;
				//
				// }
				else {

					Dao dao = (Dao) ac.getBean("daoTask");
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("jobname", nameField.getText());
					map.put("jobid", UUID.randomUUID().toString());
					map.put("markversion", rowversion.getText());
					map.put("sourcetable", sourceField.getText());
					map.put("targettable", target.getText());
					map.put("cron", cron.getText().trim());
					map.put("mapping", relationship.getText());
					map.put("queuename", config.getProperty("queue"));
					map.put("updatetime", new Timestamp(System.currentTimeMillis()));
					try {
						dao.insertMap(map, "task_info");
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				JOptionPane.showMessageDialog(contentPane, "保存成功", "提示", JOptionPane.WARNING_MESSAGE);
				dispose();
			}
		});

		button3.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

				// return;
				dispose();
			}
		});

	}

	public NewTask(String string) {

	}

}
